<?php
/**
 * 角色绑定权限
 * User: Administrator
 * Date: 2018\9\12 0012
 * Time: 16:31
 */

namespace app\Lib\Model\AdminAuth\Authorization;


use app\Lib\Exception\BlException;
use app\Lib\InterfaceIn\AdminAuth\Authorization\RoleBindingAuthHandle;
use app\Lib\InterfaceIn\AdminAuth\MenuAuthHandle;
use app\Lib\InterfaceIn\Role\RoleHandle;
use app\Lib\Model\AdminAuth\GetAuthorization\GetRoleAuth;
use app\Lib\Model\DbModel\AdminRoleAuth;

class RoleBindingAuth extends  BindingAuthBase implements  RoleBindingAuthHandle
{
    /** @var RoleHandle $role */
    private $role;
    private $roleAuthDb;
    /**
     * RoleBindingAuth constructor.
     * @param RoleHandle $role
     */
    public function __construct(RoleHandle $role)
    {
        $this->role = $role;
    }


    /**
     * @return array
     */
    private function getRoleAuth(){
        $result = (new GetRoleAuth($this->role))->run();
        $auth   = [];
        foreach ($result as $v){
            if($v instanceof  MenuAuthHandle){
                $auth[] = $v->getMenuId();
            }
        }
        return $auth;
    }

    /**
     * 删除权限
     * @param $delArray
     * @return bool
     * @throws BlException
     */
    private function delAuth($delArray){
        $model = $this->getTable();
        $map[$model->_menu_id] = ['in',$delArray];
        $result = $model->where($map)->delete();
        if(!$result){
            throw new BlException('角色权限删除失败');
        }
        return true;
    }

    /**
     * 新增权限
     * @param $addArray
     * @return bool
     * @throws BlException
     */
    private function addAuth($addArray){
        $model = $this->getTable();
        $data  = [];
        foreach ($addArray as $v){
            $array = [
                $model->_role_id=>$this->role->getRoleId(),$model->_create_time=>time(),
                $model->_menu_id=>$v,$model->_create_uid=>$this->opUser->getUid()
            ];
            $data[] = $array;
        }
        $result = $model->insertAll($data);
        if(!$result){
            throw new BlException('角色权限新增失败');
        }
        return true;
    }

    /**
     * 获取操作表
     * @return AdminRoleAuth
     */
    private function getTable(){
        if(empty($this->roleAuthDb)){
            $this->roleAuthDb = new AdminRoleAuth();
        }
        return $this->roleAuthDb;
    }


    /**
     * 执行
     * @return bool
     * @throws \app\Lib\Exception\BlException
     */
    public function run()
    {
        $auth = $this->getAuth();
        $data = $this->getRoleAuth();
        $delArray = array_diff($data,$auth);
        $addArray = array_diff($auth,$data);
        if(!empty($delArray)){
            $this->delAuth($delArray);
        }
        if(!empty($addArray)){
            $this->addAuth($addArray);
        }
        return true;
    }

}